package liveresource

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"fmt"
)

// 获取直播资源列表
func (manage *LiveResourceManage) GetLiveResourceList(query *request.GetLiveResourceListQuery) (response.PageData, error) {
	pageData := response.PageData{}

	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.LiveResource{})
	if query.AreaName != "" {
		tx = tx.Where("area_name LIKE ?", "%"+query.AreaName+"%")
	}
	if query.ChannelName != "" {
		tx = tx.Where("channel_name LIKE ?", "%"+query.ChannelName+"%")
	}

	// 获取总记录数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return pageData, err
	}
	if total == 0 {
		pageData.List = []interface{}{}
		return pageData, nil
	}

	// 分页查询
	currentPage := query.CurrentPage
	numPerPage := query.NumPerPage
	if currentPage <= 0 {
		currentPage = 1
	}
	if numPerPage <= 0 {
		numPerPage = 50
	}
	offset := (currentPage - 1) * numPerPage
	tx = tx.Order("area_name ASC, channel_name ASC").Limit(numPerPage).Offset(offset)

	var resourceList []response.GetLiveResourceListResponseInfo
	if err := tx.Find(&resourceList).Error; err != nil {
		return pageData, err
	}

	pageData.CurrentPage = currentPage
	pageData.NumPerPage = numPerPage
	pageData.TotalCount = int(total)
	pageData.TotalPages = (pageData.TotalCount + numPerPage - 1) / numPerPage
	pageData.List = resourceList

	return pageData, nil
}

// 添加或修改直播资源
func (manage *LiveResourceManage) AddOrUpdateLiveResource(liveResource *request.AddOrUpdateLiveResourceQuery) error {
	db := manage.DataBase.DB()

	isUpdate := liveResource.Id != ""

	if !isUpdate {
		resourceToCreate := dbModel.LiveResource{
			Id:          commUtils.GenUUID(),
			AreaName:    liveResource.AreaName,
			ChannelName: liveResource.ChannelName,
			PreviewUrl:  liveResource.PreviewUrl,
		}
		// 安全处理指针
		if liveResource.SignalStatus != nil {
			resourceToCreate.SignalStatus = *liveResource.SignalStatus
		}
		if err := db.Create(&resourceToCreate).Error; err != nil {
			return err
		}
	} else {
		idToUpdate := liveResource.Id
		updateData := map[string]interface{}{
			"area_name":    liveResource.AreaName,
			"channel_name": liveResource.ChannelName,
			"preview_url":  liveResource.PreviewUrl,
		}
		// 安全处理指针
		if liveResource.SignalStatus != nil {
			updateData["signal_status"] = *liveResource.SignalStatus
		}

		result := db.Model(&dbModel.LiveResource{}).Where("id = ?", idToUpdate).Updates(updateData)
		if result.Error != nil {
			return result.Error
		}
		// 检查是否有记录被更新
		if result.RowsAffected == 0 {
			return fmt.Errorf("更新直播资源失败：ID 为 %d 的记录未找到", idToUpdate)
		}
	}
	return nil
}

// 删除直播资源
func (manage *LiveResourceManage) DeleteLiveResource(liveResourceIds []string) error {
	if len(liveResourceIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	result := db.Where("id IN ?", liveResourceIds).Delete(&dbModel.LiveResource{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("没有找到要删除的记录，ID列表可能无效或记录已被删除")
	}
	return nil
}

// 获取直播资源详情
func (manage *LiveResourceManage) GetLiveResourceDetail(query *request.GetLiveResourceDetailQuery) (*response.GetLiveResourceDetailResponse, error) {
	db := manage.DataBase.DB()
	
	var liveResource dbModel.LiveResource
	if err := db.Where("id = ?", query.LiveResourceId).First(&liveResource).Error; err != nil {
		return nil, fmt.Errorf("获取直播资源详情失败：%v", err)
	}
	
	response := &response.GetLiveResourceDetailResponse{
		Id:           liveResource.Id,
		AreaName:     liveResource.AreaName,
		ChannelName:  liveResource.ChannelName,
		SignalStatus: &liveResource.SignalStatus,
		PreviewUrl:   liveResource.PreviewUrl,
	}
	
	return response, nil
}